using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ToDoList.Data;


namespace Data.Service
{
    public class UserService
    {
        private ToDoListContext _database = new ToDoListContext();
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public Users Login(string userName, string password)
        {
            var user = _database.Users.SingleOrDefault(u => u.UserName.Equals(userName) && u.Password.Equals(password));
            return user ?? null; 
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="repassword"></param>
        /// <returns></returns>
        public bool Register(string userName, string password, string repassword)
        {
            var isExist = _database.Users.SingleOrDefault(p => p.UserName.Equals(userName));
            if (isExist == null && password.Equals(repassword))
            {
                var user = new Users()
                {
                    EMail = "zvvxcv",
                    UserName = userName,
                    Password = password,
                    Birthday = DateTime.Now,
                    Sex = "男"
                };
                _database.Users.Add(user);
                _database.SaveChanges();
                return true;
            }
            else
                return false;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="password"></param>
        public void ModifyUserPassWord(int userId, string password)
        {
            var user = _database.Users.SingleOrDefault(u => u.Id == userId);
            user.Password = password;
            _database.SaveChanges();
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="userName"></param>
        public void ModifyUserInformation(int userId, string userName, string email)
        {
            var user = FindUser(userId);
            user.UserName = userName;
            user.EMail = email;
            _database.SaveChanges();
        }
        /// <summary>
        /// 查询用户
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public Users FindUser(int userId)
        {
            return _database.Users.SingleOrDefault(user => user.Id == userId);
        }
    }
}
